package com.fengyun.scala
import scala.collection.mutable
import scala.language.dynamics
/**
 * @author Hanpeng
 * @date 2021/1/26 15:37
 * @description:   一个标记trait,开启dynamic invocations(动态调用),Dynamic 的实例x,可以调用任意方法名称为
 *                 meth ,参数为 args。
 *                 从2.10开始 要实现此功能 需要导入 import scala.language.dynamics
 *                 或者打开编译器选项 -language:dynamics
 */
object TestDynamic {
  def main(args: Array[String]): Unit = {
    //foo.field           ~~> foo.selectDynamic("field")
    val person: DynamicPerson = new DynamicPerson();
    person.Name;
    println(person.Name)
    //foo.varia = 10      ~~> foo.updateDynamic("varia")(10)
    val person1: DynamicPerson1 = new DynamicPerson1()
    person1.Age = 10



  }
}
class DynamicPerson extends Dynamic{
  def selectDynamic(key:String) = {
    "你要执行的是："+key
  }


}
class DynamicPerson1 extends Dynamic{
  private val fields =mutable.HashMap.empty[String,Any].withDefault{ key => throw new NoSuchFieldError(key) }
  //获取key对应的value值
  def selectDynamic(key:String) = fields(key)
  //更新key对应的value值
  def updateDynamic(key: String)(args: Any): String ={
    println("dsdsd")
    key+args
  }
}

/*foo.method("blah")      ~~> foo.applyDynamic("method")("blah")
foo.method(x = "blah")  ~~> foo.applyDynamicNamed("method")(("x", "blah"))
foo.method(x = 1, 2)    ~~> foo.applyDynamicNamed("method")(("x", 1), ("", 2))
foo.field           ~~> foo.selectDynamic("field")
foo.varia = 10      ~~> foo.updateDynamic("varia")(10)
foo.arr(10) = 13    ~~> foo.selectDynamic("arr").update(10, 13)
foo.arr(10)         ~~> foo.applyDynamic("arr")(10)*/
